<template>
  <div class="address-manager-page">
    <NavBar>
      <template #default> 收货地址管理 </template>
    </NavBar>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>收货地址管理</span>
          <el-button type="primary" @click="openAddressDialog('add')"
            >新增地址</el-button
          >
        </div>
      </template>

      <el-table :data="addressList" v-loading="loading" style="width: 100%">
        <el-table-column label="收货人">
          <template #default="{ row }">
            <span :class="{ 'default-address-text': row.isDefault === 1 }">{{
              row.receiverName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="receiverMobile" label="手机号码" width="120" />
        <el-table-column label="所在地区" min-width="200">
          <template #default="{ row }">
            {{ row.province }} {{ row.city }} {{ row.district }}
          </template>
        </el-table-column>
        <el-table-column
          prop="detailAddress"
          label="详细地址"
          min-width="250"
        />
        <el-table-column label="默认" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isDefault === 1" type="success">默认</el-tag>
            <el-button
              v-else
              type="text"
              @click="setDefaultAddress(row.addressId)"
              >设为默认</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="openAddressDialog('edit', row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除该地址吗？"
              @confirm="deleteAddress(row.addressId)"
            >
              <template #reference>
                <el-button type="text" style="color: #f56c6c">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-empty
        v-if="!loading && addressList.length === 0"
        description="您还没有添加收货地址"
      />
    </el-card>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="addressForm"
        :rules="rules"
        ref="addressFormRef"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" />
        </el-form-item>
        <el-form-item label="手机号码" prop="receiverMobile">
          <el-input v-model="addressForm.receiverMobile" />
        </el-form-item>
        <el-form-item label="所在地区" prop="area">
          <!-- 假设您有省市区三级联动组件，这里使用简单的输入框代替 -->
          <el-input
            v-model="addressForm.province"
            placeholder="省"
            style="width: 30%"
          />
          <el-input
            v-model="addressForm.city"
            placeholder="市"
            style="width: 30%; margin-left: 5px"
          />
          <el-input
            v-model="addressForm.district"
            placeholder="区"
            style="width: 30%; margin-left: 5px"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input type="textarea" v-model="addressForm.detailAddress" />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch
            v-model="addressForm.isDefault"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitAddressForm">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import {
  getAddressList,
  addAddress,
  updateAddress,
  deleteAddressById,
  setDefaultAddressApi,
} from "@/api/AddressApi";

const addressList = ref([]);
const loading = ref(false);

const dialogVisible = ref(false);
const dialogTitle = ref("新增地址");
const addressFormRef = ref(null);
const addressForm = reactive({
  addressId: null,
  receiverName: "张三",
  receiverMobile: "15386490869",
  province: "北京市",
  city: "北京市",
  district: "东城区",
  detailAddress: "天安门小区3栋3单元",
  isDefault: 0,
});

const rules = reactive({
  receiverName: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
  ],
  receiverMobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  province: [{ required: true, message: "请输入省份", trigger: "blur" }],
  city: [{ required: true, message: "请输入城市", trigger: "blur" }],
  district: [{ required: true, message: "请输入区/县", trigger: "blur" }],
  detailAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
  ],
});

onMounted(() => {
  fetchAddressList();
});

// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true;
  try {
    const res = await getAddressList();
    if (res.data.code === 1 && res.data.data != null) {
      addressList.value = res.data.data;
    } else if (res.data.code === 1 && res.data.data == null) {
      ElMessage.info(res.data.msg + ",但暂无可用地址");
    } else {
      ElMessage.error(res.data.msg || "获取地址列表失败");
    }
  } catch (error) {
    ElMessage.error("获取地址列表失败");
  } finally {
    loading.value = false;
  }
};

// 打开新增/编辑地址弹窗
const openAddressDialog = (type, row = {}) => {
  dialogTitle.value = type === "add" ? "新增地址" : "编辑地址";
  dialogVisible.value = true;
  if (type === "edit") {
    Object.assign(addressForm, row);
  }
};

// 提交地址表单
const submitAddressForm = () => {
  addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        if (addressForm.addressId) {
          // 编辑地址
          res = await updateAddress(addressForm.addressId, addressForm);
          if (res.data.code === 1) {
            ElMessage.success("地址更新成功");
          } else {
            ElMessage.error(res.data.msg || "地址更新失败");
          }
        } else {
          // 新增地址
          res = await addAddress(addressForm);
          if (res.data.code === 1) {
            ElMessage.success("地址添加成功");
          } else {
            ElMessage.error(res.data.msg || "地址添加失败");
          }
        }
        dialogVisible.value = false;
        fetchAddressList(); // 重新加载列表
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 删除地址
const deleteAddress = async (addressId) => {
  try {
    const res = await deleteAddressById(addressId);
    if (res.data.code === 1) {
      ElMessage.success("地址删除成功");
      fetchAddressList();
    } else {
      ElMessage.error(res.data.msg || "地址删除失败");
    }
  } catch (error) {
    ElMessage.error("删除操作失败");
  }
};

// 设置默认地址
const setDefaultAddress = async (addressId) => {
  try {
    const res = await setDefaultAddressApi(addressId);
    if (res.data.code === 1) {
      ElMessage.success("默认地址设置成功");
      fetchAddressList();
    } else {
      ElMessage.error(res.data.msg || "默认地址设置失败");
    }
  } catch (error) {
    ElMessage.error("设置默认地址失败");
  }
};

// 重置表单
const resetForm = () => {
  addressFormRef.value.resetFields();
  Object.assign(addressForm, {
    addressId: null,
    receiverName: "",
    receiverMobile: "",
    province: "",
    city: "",
    district: "",
    detailAddress: "",
    isDefault: 0,
  });
};
</script>

<style scoped>
.address-manager-page {
  max-width: 1200px;
  margin: 20px auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.default-address-text {
  color: #409eff;
  font-weight: bold;
}
</style>
